package com.caifu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.mapper.SysLogMapper;
import com.caifu.mapper.SysLoginErrorMapper;
import com.caifu.mapper.SysUserMapper;
import com.caifu.pojo.SysLog;
import com.caifu.pojo.SysLoginError;
import com.caifu.pojo.SysUser;
import com.caifu.service.SysUserService;
import com.caifu.util.Constance;
import com.caifu.util.ShiroUtil;
import com.caifu.util.Util;
import com.caifu.util.Utils;
import com.caifu.vo.MenuVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 用户表 服务实现类
 * </p>
 *
 * @author Lyf
 * @since 2020-07-07
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper userMapper;
    @Resource
    private SysLogMapper logMapper;
    @Resource
    private SysLoginErrorMapper errorMapper;

    @Override
    @Transactional
    public SysUser getUserByLoginName(String loginName) throws Exception {
        try {
            return userMapper.selectOne(new QueryWrapper<SysUser>()
                    .eq("user_id", loginName)
                    .eq("status", "1"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("获取用户信息失败！");
        }
    }

    @Override
    @Transactional
    public IPage<Map<String, Object>> getUserList(int currentPage, int pageSize, String loginName, String userName, String phone, String userType) throws Exception {
        try {
            Page<SysUser> page = new Page<>(currentPage, pageSize);
            IPage<Map<String, Object>> pageList;
            QueryWrapper<SysUser> qw = new QueryWrapper();
            qw.ne("status", "9");
            if (StringUtils.isNotBlank(userName)) {
                qw.like("USER_NAME", userName);
            }
            if (StringUtils.isNotBlank(loginName)) {
                qw.like("LOGIN_NAME", loginName);
            }
            if (StringUtils.isNotBlank(phone)) {
                qw.like("PHONE", phone);
            }
            if (StringUtils.isNotBlank(userType)) {
                qw.like("POST_TYPE", userType);
            }
            qw.orderByDesc("user_no");
            pageList = userMapper.selectMapsPage(page, qw);
            /*
            if(StringUtils.isNotBlank(userName)||StringUtils.isNotBlank(loginName)||StringUtils.isNotBlank(phone)){
            	pageList = userMapper.selectMapsPage(page,new QueryWrapper<SysUser>().like("LOGIN_NAME",loginName).like("USER_NAME",userName).like("PHONE",phone).ne("status","9").orderByAsc("user_no"));
            }else{
            	pageList = userMapper.selectMapsPage(page,new QueryWrapper<SysUser>().ne("status","9").orderByAsc("user_no"));
            }*/
            //将所属机构，状态转成中文
            List<Map<String, Object>> list = pageList.getRecords();
            for (Map<String, Object> map : list) {
                String orgName = "";
                String orgStr = (String) map.get("ORG_ID");
                String postType = (String) map.get("POST_TYPE");
                map.put("ORG_NAME", orgName);

                String status = (String) map.get("STATUS");
                String statusName = ("1".equals(status) ? "开通" : "停用");
                map.put("STATUS_NAME", statusName);

            }
            return pageList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("获取用户信息失败！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateLoginTime(String loginName) throws Exception {
        try {
            UpdateWrapper<SysUser> uw = new UpdateWrapper<>();
            uw.lambda().set(SysUser::getLoginTime, Constance.currentDateTime()).eq(SysUser::getUserId, loginName);
            userMapper.update(null, uw);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("更新最后登录时间失败！");
        }
    }

    @Override
    @Transactional
    public int getCountByLoginName(String loginName, String userNo) throws Exception {
        try {
            QueryWrapper<SysUser> qw = new QueryWrapper<SysUser>();
            qw.eq("login_name", loginName);
            if (StringUtils.isNotBlank(userNo)) {
                qw.ne("user_no", userNo);
            }
            qw.ne("status", "9");
            return userMapper.selectCount(qw);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("获取用户信息失败！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setUserMenu(int userNo, String menus) throws Exception {

    }

    @Transactional
    @Override
    public Result<Object> setUserAuth(int userNo, String orgStr, int tellerNo) throws Exception {
        Result<Object> rst = new Result<>();
        SysUser user = new SysUser();
        SysUser tellerUser = new SysUser();
        try {
            user = userMapper.selectOne(new QueryWrapper<SysUser>().eq("user_no", userNo));
            if (user == null) {
                throw new Exception("在SysUser表中找不到用户信息");
            }
            tellerUser = userMapper.selectOne(new QueryWrapper<SysUser>().eq("user_no", tellerNo));
            if (tellerUser == null) {
                throw new Exception("在SysUser表中找不到用户信息");
            }

            //日志记录  sys 组织架构模块  sys-204 操作员数据权限赋权
            SysLog log = new SysLog(userNo, "1", "sys", "sys-204", "1", tellerUser.getUserId() + "对" + user.getUserId() + "设置数据权限成功！", Constance.currentDateTime());
            return ResultUtil.retLog(200, "设置数据权限成功！", log);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //日志记录  sys 组织架构模块  sys-204 操作员数据权限赋权
            SysLog log = new SysLog(userNo, "1", "sys", "sys-204", "9", tellerUser.getUserId() + "对" + user.getUserId() + "设置数据权限失败！", Constance.currentDateTime());
            return ResultUtil.retLog(201, "设置数据权限失败！", log);
        }

    }

    @Override
    @Transactional
    public Result<Object> setUserApp(int userNo, String appStr, int tellerNo) throws Exception {
        Result<Object> rst = new Result<>();
        SysUser user = new SysUser();
        SysUser tellerUser = new SysUser();
        try {
            user = userMapper.selectOne(new QueryWrapper<SysUser>().eq("user_no", userNo));
            if (user == null) {
                throw new Exception("在SysUser表中找不到用户信息");
            }
            tellerUser = userMapper.selectOne(new QueryWrapper<SysUser>().eq("user_no", tellerNo));
            if (tellerUser == null) {
                throw new Exception("在SysUser表中找不到用户信息");
            }

            //日志记录  sys 组织架构模块  sys-203 操作员开通应用
            SysLog log = new SysLog(userNo, "1", "sys", "sys-203", "1", tellerUser.getUserId() + "对" + user.getUserId() + "开通app成功[menuArray=" + appStr + "]！", Constance.currentDateTime());
            return ResultUtil.retLog(200, "开通应用成功！", log);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //日志记录  sys 组织架构模块  sys-203 操作员开通应用
            SysLog log = new SysLog(userNo, "1", "sys", "sys-203", "9", tellerUser.getUserId() + "对" + user.getUserId() + "开通app失败！", Constance.currentDateTime());
            return ResultUtil.retLog(201, "开通应用失败！", log);
        }
    }

    @Override
    @Transactional
    public void loginError(int userNo, String loginName) throws Exception {
        try {
            SysLoginError err = new SysLoginError();
            err.setUserNo(userNo);
            err.setCreateTime(new Date());
            err.setDay(Util.currentDate());
            err.setLoginName(loginName);
            errorMapper.insert(err);
            //日志记录  sys 组织架构模块  sys-205 操作员登陆
            SysLog log = new SysLog(userNo, "1", "sys", "sys-205", "9", loginName + "账号或错误, 登陆失败！", Constance.currentDateTime());
            logMapper.insert(log);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

    @Override
    @Transactional
    public void loginSuccess(int userNo, String loginName) throws Exception {
        try {
            errorMapper.delete(new QueryWrapper<SysLoginError>().eq("user_no", userNo));
            //日志记录  sys 组织架构模块  sys-205 操作员登陆
            SysLog log = new SysLog(userNo, "1", "sys", "sys-205", "1", loginName + "登陆成功！", Constance.currentDateTime());
            logMapper.insert(log);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(SysUser operUser, SysUser user, boolean isNew, String regions) {
        try {
            if (user.getUserId() != null && StringUtils.isNotBlank(user.getUserId() + "")) {
                userMapper.updateById(user);
                //日志记录  sys 组织架构模块  sys-201 操作员修改
                SysLog log = new SysLog(operUser.getId(), "1", "sys", "sys-201", "1", operUser.getUserId() + "修改操作员成功[userNo=" + user.getUserId() + "]！", Constance.currentDateTime());
                logMapper.insert(log);
            } else {
                userMapper.insert(user);
                //日志记录  sys 组织架构模块  sys-200 操作员添加
                SysLog log = new SysLog(operUser.getId(), "1", "sys", "sys-200", "1", operUser.getUserId() + "新增操作员成功[userNo=" + user.getUserId() + "]！", Constance.currentDateTime());
                logMapper.insert(log);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<MenuVo> getUserMenuById(int userNo) {
        List<MenuVo> userMenuById = userMapper.getUserMenuById(userNo);
        return formatMenu(userMenuById);
    }


    private List<MenuVo> formatMenu(List<MenuVo> userMenuById) {
        List<MenuVo> returnList = new ArrayList<>();
        //判断当前菜单是否是目录
        for (MenuVo menuVo : userMenuById) {
            //当前菜单如果是目录就存在子菜单
            if ("1".equals(menuVo.getType())) {
                //获取子菜单
                getChildMenu(menuVo, userMenuById);
                returnList.add(menuVo);
            } else if (Utils.isNull(menuVo.getParentNo())) {
                returnList.add(menuVo);
            }
        }
        return returnList;
    }

    private void getChildMenu(MenuVo menuVo, List<MenuVo> userMenuById) {
        List<MenuVo> childMenuList = new ArrayList<>();
        for (MenuVo vo : userMenuById) {
            if (menuVo.getId().equals(vo.getParentNo())) {
                childMenuList.add(vo);
            }
        }
        menuVo.setChildren(childMenuList);
    }

    @Override
    public Result updatePwd(SysUser user, String pwd) {
        //盐
        String salt = Util.getStringRandom(20);
        user.setUserPwd(ShiroUtil.sha256(pwd, salt));
        user.setSalt(salt);
        userMapper.updateById(user);
        return ResultUtil.success(200, "修改成功");
    }
}
